package com.wh.wisdomsite.xbox.server.controller.wo;

import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.wo.repairCard.*;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.DateUtils;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.Const;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import com.wh.wisdomsite.xbox.utils.server.connToserver_HttpClientClose;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 补卡controller
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.wo
 * @date 2018年10月06日 18:07
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/repairCard")
public class RepairCardController {
    private static final Log logger = LogFactory.getLog(RepairCardController.class);

    @Autowired
    private IProjectService iProjectService;

    /**
     * 跳转到补卡列表
     * @param request
     * @param prId
     * @return
     */
    @RequiresPermissions("rules:wo_repairCard_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index(HttpServletRequest request,String prId) {
        request.setAttribute("prId",prId);
        return "wo/repairCard/repairCardList";
    }

    /**
     * 获取补卡列表
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:wo_repairCard_find")
    @RequestMapping(value = "/repairCardList.do")
    public void repairCardList(HttpServletResponse response, RepairCardIn in) {
        logger.info("加载补卡列表-->>开始");
        try {
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);

            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            int total = 0;
            //获取项目名称
            String projectName = "";
            Project project = iProjectService.selectById(in.getProjectId());
            if (null != project) {
                projectName = project.getPrName();
            }
            //接口查询条件
            Map<String, String> map = new HashMap<String, String>();
            map.put("pageNumber", String.valueOf(in.getPage()));
            map.put("pageSize", String.valueOf(in.getRows()));
            map.put("projectIds", in.getProjectId());
            if(StringUtils.isNotEmpty(in.getUserName())){
                map.put("userName", in.getUserName());
            }
            //接口查询结果
            String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDREPAIRCARDLIST, map);
            //对象中存在集合的需要通过map注明集合的类型，否则会报错
            Map classMap = new HashMap();
            classMap.put("repairCards", RepairCardInfo.class);
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
            RepairCardListResult repairCardResult = (RepairCardListResult)net.sf.json.JSONObject.toBean(jsonObject, RepairCardListResult.class,classMap);
            Integer code = repairCardResult.getCode();
            //补卡信息集合
            List<RepairCardInfo> repairCards = new ArrayList<>();
            if(null != code && 1 == code){
                RepairCardList repairCardInfo = repairCardResult.getResult();
                repairCards = repairCardInfo.getRepairCards();
                total = repairCardInfo.getTotalCount();
            }
            for(RepairCardInfo repairCardInfo1 : repairCards){
                JSONObject jsonObj = new JSONObject(repairCardInfo1);
                String repairPersonId = repairCardInfo1.getRepairPerson();
                String repairPersonName = UserMapManager.getUserLoginNameInMap(repairPersonId);
                String entryDate = repairCardInfo1.getEntryDate();
                String entryDateFormat = DateUtils.dateStrChangeToTime(entryDate);
                jsonObj.put("projectName",projectName);
                jsonObj.put("repairPerson",repairPersonName);
                jsonObj.put("entryDate",entryDateFormat);
                array.put(jsonObj);
            }
            json.put("total", total);
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取补卡列表-->Exception " + e.getMessage());
        }
    }

    /**
     * 补卡详情
     * @param id
     * @param projectName
     * @param request
     * @return
     */
    @RequiresPermissions("rules:wo_repairCard_view")
    @RequestMapping(value = "/repairCardDesc.do")
    public String repairCardDesc(String id,String projectName, HttpServletRequest request) {
        logger.info("补卡详情-->>开始");
        RepairCardInfo repairCardInfo = new RepairCardInfo();
        //录入时间
        String entryDateFormat = "";
        //补卡人
        String repairPersonName = "";
        try{
            if(StringUtils.isNotEmpty(id)){
                //接口查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("repairCardId", id);
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDREPAIRCARDGETBYID, map);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                //补卡详情
                RepairCardDetail repairCardDetail = (RepairCardDetail)net.sf.json.JSONObject.toBean(jsonObject, RepairCardDetail.class);
                repairCardInfo = repairCardDetail.getResult();
                entryDateFormat = DateUtils.dateStrChangeToTime(repairCardInfo.getEntryDate());
                repairPersonName = UserMapManager.getUserLoginNameInMap(repairCardInfo.getRepairPerson());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        request.setAttribute("repairCard",repairCardInfo);
        request.setAttribute("projectName",projectName);
        request.setAttribute("entryDate",entryDateFormat);
        request.setAttribute("repairPersonName",repairPersonName);
        logger.info("补卡详情-->>结束");
        return "wo/repairCard/repairCardDesc";
    }


    /**
     * 跳转至添加或修改页面
     * @param id
     * @param projectName
     * @param request
     * @param prId
     * @return
     */
    @RequestMapping("/toRepairCardOption.do")
    public String toRepairCardOption(String id,String projectName, HttpServletRequest request,String prId){
        logger.info("添加修改补卡跳转-->>开始");
        RepairCardInfo repairCardInfo = new RepairCardInfo();
        //补卡人
        String repairPersonName = "";
        //录入时间
        String entryDateFormat = "";
        try{
            if(StringUtils.isNotEmpty(id)){
                //接口查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("repairCardId", id);
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDREPAIRCARDGETBYID, map);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                //补卡信息
                RepairCardDetail repairResult = (RepairCardDetail)net.sf.json.JSONObject.toBean(jsonObject, RepairCardDetail.class);
                repairCardInfo = repairResult.getResult();
                String userId = repairCardInfo.getRepairPerson();
                repairPersonName = UserMapManager.getUserLoginNameInMap(userId);
                String entryDate = repairCardInfo.getEntryDate();
                entryDateFormat = DateUtils.dateStrChangeToTime(entryDate);
                prId = repairCardInfo.getProjectId();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        request.setAttribute("repairCard",repairCardInfo);
        request.setAttribute("repairPersonName",repairPersonName);
        request.setAttribute("entryDate",entryDateFormat);
        request.setAttribute("projectName",projectName);
        request.setAttribute("projectId",prId);
        logger.info("添加修改补卡跳转-->>结束");
        return "wo/repairCard/repairCardOption";
    }

    /**
     * 保存补卡信息
     * @param repairCardInfo
     * @param response
     */
    @RequiresPermissions("rules:wo_repairCard_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save( RepairCardInfo repairCardInfo,HttpServletResponse response) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //补卡信息更新或添加url
            String url = "";
            if(StringUtils.isNotEmpty(repairCardInfo.getRepairCardId())){
                url = Const.WORKER_ATTENDREPAIRCARDUPDATE;
            }else{
                url = Const.WORKER_ATTENDREPAIRCARD;
            }
            //设置接口保存数据
            Map<String, String> map = new HashMap<String, String>();
            map.put("repairCardId", repairCardInfo.getRepairCardId());
            map.put("cardRepairDate", repairCardInfo.getCardRepairDate());
            map.put("repairStartDate", repairCardInfo.getRepairStartDate());
            map.put("repairEndDate", repairCardInfo.getRepairEndDate());
            map.put("workingHours", repairCardInfo.getWorkingHours());
            map.put("repairReason", repairCardInfo.getRepairReason());
            map.put("repairPerson", UserUtils.getCurrentUser().getUsId());
            map.put("entryDate", sdf.format(new Date()));
            map.put("idCard", repairCardInfo.getIdCard());
            map.put("projectId", repairCardInfo.getProjectId());
            map.put("userId", repairCardInfo.getUserId());
            map.put("userName", repairCardInfo.getUserName());
            map.put("sex", repairCardInfo.getSex());
            map.put("groupName", repairCardInfo.getGroupName());
            //保存结果
            String result = connToserver_HttpClientClose.sendPostRequest(url, map);
            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
            RepairCardSaveResult repairResult = (RepairCardSaveResult)net.sf.json.JSONObject.toBean(jsonObject, RepairCardSaveResult.class);
            Integer code = repairResult.getCode();
            if(1 == code){
                response.getWriter().write(JsonUtil_Org.returnTrue("保存补卡信息成功"+"-"+repairCardInfo.getProjectId()));
            }else{
                response.getWriter().write(JsonUtil_Org.returnFalse("保存补卡信息失败"+"-"+repairCardInfo.getProjectId()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加补卡-->>Exception" + e.getMessage());
        }
    }


    /**
     * 条件查询补卡信息
     * @param repairCardInfo
     * @param response
     */
    @RequestMapping("/getRepairByCondition.do")
    public void getRepairByCondition(RepairCardInfo repairCardInfo, HttpServletResponse response){
        logger.info("条件查询补卡信息-->>开始");
        String idCard = repairCardInfo.getIdCard();
        String projectId = repairCardInfo.getProjectId();
        String cardRepairDate = repairCardInfo.getCardRepairDate();
        String repairTime = "";
        String entryDate = "";
        String repairPerson = "";
        String repairReason = "";
        JSONObject obj = new JSONObject();
        try{
            if(StringUtils.isNotEmpty(idCard) && StringUtils.isNotEmpty(projectId) &&
                StringUtils.isNotEmpty(cardRepairDate)){
                //接口查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("idCard", idCard);
                map.put("projectId", projectId);
                map.put("cardRepairDate", cardRepairDate);
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_ATTENDREPAIRGETBYCONDITION, map);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                Map classMap = new HashMap();
                classMap.put("result", RepairCardInfo.class);
                RepairCardDetailList repairResult = (RepairCardDetailList)net.sf.json.JSONObject.toBean(jsonObject, RepairCardDetailList.class,classMap);
                //补卡信息集合
                List<RepairCardInfo> result1 = repairResult.getResult();
                for(RepairCardInfo repairInfo : result1){
                    String repairStartDate = repairInfo.getRepairStartDate();
                    String repairEndDate = repairInfo.getRepairEndDate();
                    String repairStartDate1 = repairStartDate.substring(repairStartDate.indexOf(" ")+1,repairStartDate.length());
                    String repairEndDate1 = repairEndDate.substring(repairEndDate.indexOf(" ")+1,repairEndDate.length());
                    //补卡时间拼接(一天可能存在多个补卡时间)
                    repairTime = repairTime + repairStartDate1 + "-" + repairEndDate1 + ";";
                    //获取补卡录入时间
                    String entryDate1 = repairInfo.getEntryDate();
                    String entryDateFormat = DateUtils.dateStrChangeToTime(entryDate1);
                    entryDate = entryDate + entryDateFormat + ";";
                    //补卡人
                    String repairPersonId = repairInfo.getRepairPerson();
                    String repairPersonName = UserMapManager.getUserLoginNameInMap(repairPersonId);
                    repairPerson = repairPerson + repairPersonName + ";";
                    //补卡原因
                    String repairReason1 = repairInfo.getRepairReason();
                    repairReason = repairReason + repairReason1 + "---";
                }
            }
            obj.put("repairTime",repairTime);
            obj.put("entryDate",entryDate);
            obj.put("repairPerson",repairPerson);
            obj.put("repairReason",repairReason);
            obj.put("cardRepairDate",cardRepairDate);
        }catch (Exception e){
            e.printStackTrace();
        }
        ResManager.getJsonOut(response).print(obj);
    }

}
